package com.wenhai.xiaomage.spring.ioc.overview.dependency.container;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Arrays;
import java.util.Map;

/**
 * @Author:wenhai
 * @Description: {@link org.springframework.context.annotation.AnnotationConfigApplicationContext}
 * @Date:2020/3/24
 */
public class AnnotationApplicationContextAsIoCContainerDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(AnnotationApplicationContextAsIoCContainerDemo.class);
        applicationContext.refresh();
        lookupCollectionByType(applicationContext);
        DefaultListableBeanFactory dbf = applicationContext.getDefaultListableBeanFactory();
        System.out.println(Arrays.toString(dbf.getDependentBeans("createUser")));
        System.out.println(Arrays.toString(dbf.getDependenciesForBean("dependentBean")));
        applicationContext.close();
    }


    private static void lookupCollectionByType(BeanFactory beanFactory) {
        System.out.println("类型查找集合对象");
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> userMap = listableBeanFactory.getBeansOfType(User.class);
            System.out.println(userMap);
        }
    }


    @Bean
    public User createUser() {
        User user = new User(2L);
        user.setUsername("谢文海");
        return user;
    }

    @Bean
    public String dependentBean(User user) {

        return "bei";
    }
}
